package com.shanghaionstar.login;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.EncryptUtil;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.login.iview.ILoginView;
import com.shanghaionstar.login.presenter.LoginPresenter;
import com.shanghaionstar.login.register.JoinMeVinActivity;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;

import java.lang.reflect.Field;

/**
 * Created by 6335yz on 2016/5/5.
 */
@ContentView(R.layout.login_home)
public class LoginActivity extends SwipeActivity implements ILoginView {
    public final static int REQUEST_SUPPLEMENT = 100;

    public final static int REQUEST_VERIFY_INFO3 = 101;
    @FindViewById
    private ProgressLayout login_progress;

    @FindViewById
    private CustomImageView img_onstar_edit_displaypwd;

    private LoginPresenter loginPresenter;

    @FindViewById
    private DeleteEditText et_login_name, et_login_pass;

    private boolean isShowPwd = false;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
//        if (!CommonUtil.isNull(et_login_name.getText())) {
//            outState.putString("et_login_name", String.valueOf(et_login_name.getText()));
//        }
//        if (!CommonUtil.isNull(et_login_pass.getText())) {
//            outState.putString("et_login_pass", String.valueOf(et_login_pass.getText()));
//        }
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
//        if (savedInstanceState != null) {
//            et_login_name.setText(savedInstanceState.getString("et_login_name"));
//            et_login_pass.setText(savedInstanceState.getString("et_login_pass"));
//        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        overridePendingTransition(R.anim.bottom_enter, R.anim.bottom_out);
        super.onCreate(savedInstanceState);
//        if (savedInstanceState != null) {
//            et_login_name.setText(savedInstanceState.getString("et_login_name"));
//            et_login_pass.setText(savedInstanceState.getString("et_login_pass"));
//        }
        if (getIntent().getIntExtra(RxConstants.ACTION_NAME, 0) != 0) {
        }
        loginPresenter = new LoginPresenter(getScheduler(), this);
        loginPresenter.setView(this);


        if (getIntent().getBooleanExtra("isUpgradeToSub", false)) {
            Intent intent = new Intent(onActivity(), JoinMeVinActivity.class);
            intent.putExtra("isUpgradeToSub", true);
            onActivity().startActivityForResult(intent, Constants.REQ_CODE_JOINME);
            finish();
        }
        loginPresenter.onResume();
    }


    @Override
    protected void onResume() {
        super.onResume();
        loginPresenter.onResume();
//        et_login_name.setText("13200938812");
//        et_login_pass.setText("Admin123");
    }

    @OnClick({R.id.btn_login, R.id.btn_register, R.id.forgot_pass, R.id.img_login_close, R.id.img_onstar_edit_displaypwd})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                loginPresenter.login(String.valueOf(et_login_name.getText()), String.valueOf(et_login_pass.getText()));
                break;
            case R.id.btn_register:
                loginPresenter.doRegister();
                break;
            case R.id.forgot_pass:
                loginPresenter.forgetPwd();
                break;
            case R.id.img_login_close:
                BusinessUtil.sendReportByClickType(this, FunctionNameFindId.loginregister_Close.getStringValue());//登录——关闭
                setResult(Activity.RESULT_CANCELED);
                onFinish();
                break;
            case R.id.img_onstar_edit_displaypwd:
                /**
                 * eye to show pwd or not,
                 * try to use custom view;
                 */
                isShowPwd = !isShowPwd;
                if (isShowPwd) {
                    et_login_pass.isShowPassword(true);
                    img_onstar_edit_displaypwd.setImageResource(R.drawable.common_pwd_eye_click);
                } else {
                    et_login_pass.isShowPassword(false);
                    img_onstar_edit_displaypwd.setImageResource(R.drawable.common_pwd_eye);
                }
                break;
            default:
                break;
        }
        CommonUtil.hideKeyBoard(LoginActivity.this, et_login_name);
    }

    @Override
    public void showUpgrade(final OnStarException e) {
        AlertDialogUtil.showAlertDialog(LoginActivity.this, R.string.E9004,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!CommonUtil.isNull(e.getMessage())) {
                            Intent intent = new Intent("android.intent.action.VIEW");
                            if (!e.getMessage().contains("http")) {
                                intent.setData(Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.shanghaionstar"));
                            } else {
                                intent.setData(Uri.parse(e.getMessage()));
                            }
                            startActivity(intent);
                            finish();
                        } else {
                            dialog.dismiss();
                        }
                    }
                }, null);
    }

    @Override
    public void setEditNameValue(String name) {
        et_login_name.setText(name);
    }

    @Override
    public void setEditPwdValue(String pwd) {
        et_login_pass.setText(pwd);
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void setLoading(boolean isLoading) {
        final int visibile = isLoading ? View.VISIBLE : View.GONE;
        login_progress.setVisibility(visibile);
    }

    @Override
    public void onResponseError(OnStarException e) {
        setLoading(false);
        AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning),
                e.getMessage());
    }

    @Override
    public void onReponseSuccess(Object object) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        et_login_name.onDestory();
        et_login_pass.onDestory();
        et_login_pass = null;
        et_login_name = null;
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    public void onFinish() {
        setLoading(false);
        loginPresenter.unRegisterSubscriber();
        finish();
    }

    /**
     * Info3.0非app注册用户验证提示
     */
    AlertDialog info3AlertDialog;

    @Override
    public void verifyInfo3() {
        BusinessUtil.clearOnstarAppContext(this);
        if (info3AlertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage(getString(R.string.verify_info3_tip));
            builder.setPositiveButton(getString(R.string.verify_info3_now), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
//                    setClosable(info3AlertDialog,false);
//                    Intent intentWeb = new Intent(LoginActivity.this, CommonWebViewActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putString("topTitle",getString(R.string.verify_info3));
//                    bundle.putString("linkUrl", verifyLink);
//                    intentWeb.putExtras(bundle);
//                    startActivityForResult(intentWeb,REQUEST_VERIFY_INFO3);
                    String verifyLink = Constants.CURRENT_PREFIX_H5_URL + Constants.INFO3_VERIFY_ZH + "?username=" + et_login_name.getText().toString() + "&type=app";
                    WebDataEntity entity = new WebDataEntity();
                    entity.setTopTitle(getString(R.string.verify_info3));
                    entity.setLinkUrl(verifyLink);
                    CommonWebViewActivity.launchCommonWebForResult(LoginActivity.this, null, entity, REQUEST_VERIFY_INFO3);
                    BusinessUtil.sendReportByClickType(LoginActivity.this, FunctionNameFindId.LoginVerification_Info3UnverifiedUser.getStringValue());

                }
            });
            info3AlertDialog = builder.create();
            info3AlertDialog.setCanceledOnTouchOutside(false);
//            info3AlertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                @Override
//                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                    if(keyCode == KeyEvent.KEYCODE_BACK)
//                        return true;
//                    return false;
//                }
//            });
        }
        info3AlertDialog.show();
    }

    private void setClosable(Dialog dialog, boolean closeable) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, closeable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void finish() {
        super.finish();
//        overridePendingTransition(R.anim.bottom_enter, R.anim.bottom_out);
//        overridePendingTransition(R.anim.left_in, R.anim.right_out);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onActivityResult", "onActivityResult");
        if (resultCode == RESULT_OK && requestCode == REQUEST_SUPPLEMENT) {
            loginPresenter.login(String.valueOf(et_login_name.getText()), String.valueOf(et_login_pass.getText()));
        } else if (requestCode == REQUEST_SUPPLEMENT) {
            setLoading(false);
        } else if (resultCode == REQUEST_VERIFY_INFO3) {
//            setClosable(info3AlertDialog,true);
            info3AlertDialog.dismiss();
            loginPresenter.login(String.valueOf(et_login_name.getText()), String.valueOf(et_login_pass.getText()));
        }
    }
}
